package com.funsport.controller.web;

import com.funsport.common.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/upload")
@Tag(name = "文件上传")
public class WebFileController {
    
    @Value("${file.upload.path:/tmp/uploads}")
    private String uploadPath;
    
    @Value("${file.upload.url:http://localhost:8858/uploads}")
    private String uploadUrl;
    
    @Operation(summary = "上传图片")
    @PostMapping("/image")
    public Result<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return Result.error("只能上传图片文件");
        }
        
        // 检查文件大小（最大5MB）
        if (file.getSize() > 5 * 1024 * 1024) {
            return Result.error("文件大小不能超过5MB");
        }
        
        try {
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String filename = UUID.randomUUID().toString().replace("-", "") + extension;
            
            // 创建目录
            String relativePath = "images/" + dateStr;
            Path dirPath = Paths.get(uploadPath, relativePath);
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
            }
            
            // 保存文件
            Path filePath = dirPath.resolve(filename);
            file.transferTo(filePath.toFile());
            
            // 返回URL
            String url = uploadUrl + "/" + relativePath + "/" + filename;
            
            Map<String, String> result = new HashMap<>();
            result.put("url", url);
            result.put("filename", filename);
            
            log.info("文件上传成功: {}", url);
            return Result.success(result);
            
        } catch (IOException e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            return Result.error("文件上传失败");
        }
    }
    
    @Operation(summary = "上传多张图片")
    @PostMapping("/images")
    public Result<Map<String, Object>> uploadImages(@RequestParam("files") MultipartFile[] files) {
        if (files == null || files.length == 0) {
            return Result.error("请选择文件");
        }
        
        if (files.length > 9) {
            return Result.error("最多只能上传9张图片");
        }
        
        java.util.List<Map<String, String>> urls = new java.util.ArrayList<>();
        
        for (MultipartFile file : files) {
            Result<Map<String, String>> result = uploadImage(file);
            if (result.getCode() == 200) {
                urls.add(result.getData());
            }
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("count", urls.size());
        response.put("urls", urls);
        
        return Result.success(response);
    }
}

